import store from "@/store"
import mTool from '../common/tools.js'
import mRoutesConfig from '@/config/routes.config.js'
import { loadUserInfo } from '@/config/cache';
function HTTP(obj, config) {

	let defaultConfig = {
		isRes: false,
		loading: true
	}

	config = { ...defaultConfig,
		...config
	}


	config.loading && uni.showLoading({
		title: '加载中',
		mask: true
	});

	return new Promise((resolve, reject) => {

		let options = {
			url: "",
			method: "GET",
			data: {},
			dataType: "json",
			header: {
				"content-type": "application/json",
				"X-requested-With": "XMLHttpRequest",
			},
			success: (res) => {
				// console.log("HTTP请求结果：",res);
				uni.stopPullDownRefresh();
				uni.hideLoading();
				// 状态码为200
				if (res.statusCode == 200) {
					let data = res.data;
					if (data.errcode == "200") {
						resolve(data.data);
					} else if(data.errcode == "996"){
						store.dispatch('appLogout');
						if (!config.noToast) {
							wx.showToast({
								title: "未登录或登录失效,请重新登录",
								icon: "none",
								duration: 3000
							})
							jumpLogin()
						}
						reject(data.errcode);
					}else {
						wx.showToast({
							title: data.errmsg,
							icon: "none",
							duration: 2000
						})
						reject(data.errmsg);
					}
				} else if (res.statusCode == 404) {
					wx.showToast({
						title: "无法访问此网站，请检查请求是否正确",
						icon: "none",
						duration: 3000
					})
				} else if (res.statusCode == 500) {
					wx.showToast({
						title: "服务器错误，请联系管理员",
						icon: "none",
						duration: 3000
					})
				} else {
					reject("HTTP:状态码异常！");
				}
			},
			fail: (err) => {
				console.log(err);
				uni.hideLoading();
				uni.stopPullDownRefresh();
				uni.showToast({
					title: "网络异常，请稍后再试!",
					icon: "none",
				})
				reject("网络异常，请稍后再试!");
			},
			complete: () => {}
		}

		options = { ...options,
			...obj
		};
		// if(options.method=="POST"){
		// 	options.header['content-type'] = "application/x-www-form-urlencoded";
		// }
		if (options.url && options.method) {
			wx.request(options);
		} else {
			wx.showToast({
				title: 'HTTP：缺失参数',
				icon: "none",
				duration: 2000
			})
		}
	})

}
function fixData(data) {
	let token = store.state.token
	if(!token.username) return data
	let timestamp = new Date().getTime()
	let mac =  mTool.getMacMD5(token.userid, timestamp)
	return {
		...token,
		...data,
		timestamp,
		mac
	}
}



export default {
	GET(url, undata = {}, config) {
		let data = fixData(undata)
		return HTTP({
			url,
			data,
			method: "GET"
		}, config);
	},
	POST(url, undata = {}, config) {
		// console.log("HTTP上送URL" + url);
		let data = fixData(undata)
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	},

	POSTformdata(url, data = {}, config) {
		return HTTP({
			url,
			data,
			method: "POST"
		}, config);
	},
	
}

function jumpLogin() {
	let loggingSign = store.state.oneLogin
    if (loggingSign) {
        return
    }
	store.dispatch('loginLoading')
    let pages = getCurrentPages();
    let page = pages[pages.length - 1];
	console.log(page);
    if (page.route.indexOf("/pages/app/login") > -1 || page.route.indexOf("/pages/app/index") > -1) {
        return
    }
    uni.removeStorageSync('token')
	let redirectUrl = mTool.objParseUrlAndParam(page.route, {
		...page.options 
	})
    uni.setStorageSync('loginBefore', '/'+redirectUrl);
    uni.redirectTo({
        url: '/pages/app/login'
    });
}